package com.wxd.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccessDB {
	public synchronized static void closeConn(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				conn = null;
			}
		}
	}

	public synchronized static void close(Connection conn, Statement stmt, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				rs = null;
			}
		}

		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				stmt = null;
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				conn = null;
			}
		}
	}

	public synchronized static void close(Connection conn, PreparedStatement pstm,
			ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				rs = null;
			}
		}

		if (pstm != null) {
			try {
				pstm.close();
			} catch (SQLException e) {
				pstm = null;
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				conn = null;
			}
		}
	}

	public static synchronized List queryForSql(String sql,boolean flag) {
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		List list = new ArrayList();
		try {
			conn = ConnectionManager.getInstance().getConnection();
			pstm = conn.prepareStatement(sql);
			rs = pstm.executeQuery();

			ResultSetMetaData metaData = rs.getMetaData();

			int columnCount = metaData.getColumnCount();

			while (rs.next()) {
				Map<Integer, Object> map = new HashMap<Integer, Object>();
				for (int n = 1; n <= columnCount; n++) {
					Object object = rs.getObject(n);
					map.put(n, object);
				}
				list.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			AccessDB.close(conn, pstm, rs);
		}
		return list;
	}
	
	
	public static synchronized boolean executeSql(String sql,boolean flag){
		Connection conn = null;
		PreparedStatement pstm = null;
		try{
			conn = ConnectionManager.getInstance().getConnection();
			
			pstm = conn.prepareStatement(sql);
			
			int i = pstm.executeUpdate();
			if(i>0){
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			AccessDB.close(conn, pstm,null);
		}
		return false;
	}

}
